/*
 * 把bot的动作记录到数据库
 * v0.1
 */
package main;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.Date;

public class Action2Log {

	/**
	 * 格式化log
	 * 
	 * @param sentence
	 * @param user
	 * @param finalSentence
	 * @return
	 */
	static private String formatLog(SentencePair sentence, UserLite user,
			String finalSentence) {
		StringBuffer log = new StringBuffer();
		// add time to log
		log.append("[");
		log.append(Common.DEFAULT_TIME_YMDHMS.format(new Date(System
				.currentTimeMillis())));
		log.append("]");
		if (user != null) {
			log.append(" SET user : @").append(user.getScreenName())
					.append("(").append(user.getId())
					.append(") TO SENTENCE : ").append(sentence.getId());
		}
		log.append(" UPDATING :[").append(finalSentence).append("]");
		return log.toString();
	}

	/**
	 * 插入log
	 * 
	 * @param sentence
	 * @param user
	 * @param finalSentence
	 */
	static public void insertLog(SentencePair sentence, UserLite user,
			String finalSentence) {
		try {
			Connection conn = new Dao().getConn();
			StringBuffer sql = new StringBuffer(
					"INSERT INTO LOGS SET LOGS = ? , RELATED_SENTENCE = ? , LAST_UPDATE = ?");
			if (user != null) {
				sql.append(" , RELATED_FRIEND = ?");
			}
			String formatedLog = formatLog(sentence, user, finalSentence);
			PreparedStatement prst = conn.prepareStatement(sql.toString());
			prst.setString(1, formatedLog);
			prst.setLong(2, sentence.getId());
			prst.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
			if (user != null) {
				prst.setLong(4, user.getId());
			}
			prst.execute();
			System.out.println(formatedLog);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
